<script setup>
import { userService_UpdatePwd } from '@/apis/user'
import { ElMessage } from 'element-plus'
import { ref } from 'vue'
let title = ref('基本资料')
const passwordForm = ref({
  old_pwd: '',
  new_pwd: '',
  re_pwd: ''
})

let myRule = ref({
  // 注意：表单验证不能写成驼峰
  old_pwd: [{ required: true, message: '请输入原密码', trigger: 'blur' }],
  // 表单验证不能写成驼峰
  new_pwd: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    { min: 6, max: 15, message: '长度必须在6~15个字符之间', trigger: 'blur' }
  ],
  re_pwd: [
    {
      required: true,
      message: '请确认密码',
      trigger: 'blur'
    },
    {
      // 校验的规则，获取到的值
      validator: (rule, value, callback) => {
        if (value === '') {
          return callback(new Error('密码不能为空'))
        }
        if (passwordForm.value.new_pwd !== value) {
          callback(new Error('两次密码不一致'))
          return
        }
        callback()
      },
      trigger: 'blur'
    }
  ]
})

// ---------- 方法区 ----------
const updatePwd = async () => {
  if (passwordForm.value.old_pwd === '') {
    return ElMessage({
      type: 'error',
      message: '请输入旧密码'
    })
  }
  if (passwordForm.value.new_pwd === '') {
    return ElMessage({
      type: 'error',
      message: '请输入新密码'
    })
  }
  if (passwordForm.value.re_pwd === '') {
    return ElMessage({
      type: 'error',
      message: '请重新输入密码'
    })
  }
  // 验证旧密码是否正确【后端做的事】

  // 修改为新密码
  await userService_UpdatePwd(passwordForm.value)
  ElMessage({
    type: 'success',
    message: '修改成功'
  })
}
</script>

<template>
  <CardPage :title="title">
    <template #extra>
      <el-form
        ref="ruleFormRef"
        :model="passwordForm"
        :rules="myRule"
        label-width="120px"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="原密码" prop="old_pwd">
          <el-input v-model="passwordForm.old_pwd" size="large" />
        </el-form-item>
        <el-form-item label="新密码" prop="new_pwd">
          <el-input v-model="passwordForm.new_pwd" size="large" />
        </el-form-item>

        <el-form-item label="确认新密码" prop="re_pwd">
          <el-input v-model="passwordForm.re_pwd" size="large" />
        </el-form-item>

        <el-form-item label="">
          <el-button type="primary" @click="updatePwd">修改密码</el-button>
          <el-button type="default">重置</el-button>
        </el-form-item>
      </el-form>
    </template>
  </CardPage>
</template>

<style lang="scss" scoped>
:deep .el-form-item__content {
  flex: none;
  width: 550px;
}
</style>
